cmake_minimum_required(VERSION 3.8)
project(mpc_planner_solver)

# C++ Standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

# Check if solver.cmake exists
if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/solver.cmake")
    message(FATAL_ERROR
        "solver.cmake not found!\n"
        "Please generate a solver first by running:\n"
        "  export ACADOS_SOURCE_DIR=/home/gao/acados\n"
        "  export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/gao/acados/lib\n"
        "  export PYTHONPATH=$PYTHONPATH:/home/gao/acados/interfaces/acados_template\n"
        "  python3 mpc_planner_jackalsimulator/scripts/generate_jackalsimulator_solver.py"
    )
endif()

# Include solver configuration (generated by Python script)
include(solver.cmake)

# Find dependencies
if(NOT TARGET mpc_planner_util)
    find_package(mpc_planner_util REQUIRED)
endif()

if(NOT TARGET ros_tools_no_ros)
    find_package(ros_tools_no_ros REQUIRED)
endif()

# Include directories
include_directories(
  include
  ${solver_INCLUDE_DIRS}
)

# Build library
add_library(${PROJECT_NAME} SHARED
  src/mpc_planner_parameters.cpp
  src/state.cpp
  ${solver_SOURCES}
)

# Add compile definitions
target_compile_definitions(${PROJECT_NAME} PUBLIC ACADOS_SOLVER)

# Link libraries
target_link_libraries(${PROJECT_NAME}
  mpc_planner_util
  ros_tools_no_ros
  ${solver_LIBRARIES}
)

# Export include directories
target_include_directories(${PROJECT_NAME} PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
  $<INSTALL_INTERFACE:include>
)

# Add solver include directories
foreach(solver_inc_dir ${solver_INCLUDE_DIRS})
  # Check if path is absolute
  if(IS_ABSOLUTE ${solver_inc_dir})
    target_include_directories(${PROJECT_NAME} PUBLIC
      $<BUILD_INTERFACE:${solver_inc_dir}>
    )
  else()
    target_include_directories(${PROJECT_NAME} PUBLIC
      $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/${solver_inc_dir}>
    )
  endif()
endforeach()

# Install
install(TARGETS ${PROJECT_NAME}
  EXPORT ${PROJECT_NAME}Targets
  ARCHIVE DESTINATION lib
  LIBRARY DESTINATION lib
  RUNTIME DESTINATION bin
)

install(DIRECTORY include/${PROJECT_NAME}/
  DESTINATION include/${PROJECT_NAME}
  PATTERN ".svn" EXCLUDE
)
